<template>
    <div>
        <div>
            <el-config-provider :locale="zhCn"> <!--《:locale="zhCn 》设置语言-->

                <el-scrollbar height="70vh">
                    <!-- 补卡申请 -->
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                                <el-form-item label="补卡申请" label-position="top"
                                    :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                                    <div class="progress-bar">
                                        <div class="progress"></div>
                                    </div>
                                </el-form-item>

                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="申请日期"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.applicationDate"
                                        style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="归属考勤周期"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.attendanceCycle"
                                        style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="姓名" label-position="top"
                                    required>
                                    <el-input :placeholder="user.employeeName" style="/*width: 354px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="所在部门" label-position="top"
                                    required>
                                    <el-input :placeholder="user.department.deptName" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="上班要求时间"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.startTime" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="下班要求时间"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.endTime" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="补签日期" label-position="top"
                                    required>
                                    <div style="display: flex; flex-direction: column;">
                                        <span style="font-size: 12px;">选择需要补签的日期</span>
                                        <el-date-picker v-model="formData.retroactiveDate" style="width: 354px;"
                                            type="date" placeholder="" :size="size" value-format="YYYY-MM-DD" />
                                    </div>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="星期" label-position="top">
                                    <span style="font-size: 12px;">补签当天的星期数</span>
                                    <el-input placeholder="" v-model="formData.week" style="/*width: 354px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light">
                                <el-form-item label="补签时间段" label-position="top" required>
                                    <el-radio-group v-model="formData.timeBucket">
                                        <el-radio value="上午签到" size="large"
                                            v-if="canSignMorning(attendanceRecord.morningStatus)">
                                            <el-tag type="success" size="normal" effect="dark">上午签到</el-tag>
                                        </el-radio>
                                        <el-radio value="下午签退" size="large"
                                            v-if="canSignAfternoon(attendanceRecord.afternoonStatus)">
                                            <el-tag type="primary" size="normal" effect="dark">下午签退</el-tag>
                                        </el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="补签事由说明"
                                    label-position="top" required>
                                    <el-input v-model="formData.reason" style="width: 633px;" :rows="6" type="textarea"
                                        placeholder="" />
                                </el-form-item>
                            </div>
                        </el-col>

                        <div class="bottom-submit-bar">
                            <el-button type="primary" @click="onSubmit">提交</el-button>
                        </div>

                    </el-row>
                </el-scrollbar>

            </el-config-provider>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, defineEmits } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router';
import request from '@/api/request';

let emits = defineEmits(['ref-table']);

//获取全局的考勤规则
const attendanceRule = ref({});

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');

const formData = ref({
    applicationDate: '',
    retroactiveDate: '',
})

let loadAttendanceRules = () => {
    request({
        url: "/attendanceRule/rules",
        method: "get"
    }).then(resp => {
        attendanceRule.value = resp.data;
    })
};

const attendanceRecord = ref({})

// 获取当前日期字符串 YYYY-MM-DD
const getCurrentDateStr = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 新增函数：判断是否可以补签上午
const canSignMorning = (status) => {
    // 如果不是补签当天，则可以补签上午
    if (formData.value.retroactiveDate !== getCurrentDateStr()) {
        return ['迟到', '缺勤', '未签到'].includes(status);
    }

    // 如果是补签当天，需要判断当前时间是否超过上班时间+迟到容忍时间
    const now = new Date();

    // 获取考勤规则中的上班时间和迟到容忍时间
    const workStart = attendanceRule.value.workStart || '08:30:00';
    const lateTolerance = attendanceRule.value.lateTolerance || 30; // 分钟

    // 解析工作开始时间
    const [workHours, workMinutes] = workStart.split(':').map(Number);

    // 计算允许补签的最早时间（上班时间 + 迟到容忍时间）
    const allowedStartTime = new Date();
    allowedStartTime.setHours(workHours);
    allowedStartTime.setMinutes(workMinutes + lateTolerance);
    allowedStartTime.setSeconds(0);
    allowedStartTime.setMilliseconds(0);

    // 只有在允许的时间之后才能补签上午的记录
    return now >= allowedStartTime && ['迟到', '缺勤', '未签到'].includes(status);
};

// 新增函数：判断是否可以补签下午
const canSignAfternoon = (status) => {
    // 如果不是补签当天，则可以补签下午
    if (formData.value.retroactiveDate !== getCurrentDateStr()) {
        return ['早退', '缺勤', '未签到'].includes(status);
    }

    // 如果是补签当天，需要判断当前时间是否超过下班时间-早退容忍时间
    const now = new Date();

    // 获取考勤规则中的下班时间和早退容忍时间
    const workEnd = attendanceRule.value.workEnd || '18:00:00';
    const earlyLeaveTolerance = attendanceRule.value.earlyLeaveTolerance || 30; // 分钟

    // 解析工作结束时间
    const [endHours, endMinutes] = workEnd.split(':').map(Number);

    // 计算允许补签的最晚时间（下班时间 - 早退容忍时间）
    const allowedEndTime = new Date();
    allowedEndTime.setHours(endHours);
    allowedEndTime.setMinutes(endMinutes - earlyLeaveTolerance);
    allowedEndTime.setSeconds(0);
    allowedEndTime.setMilliseconds(0);

    // 只有在允许的时间之前才能补签下午的记录
    return now <= allowedEndTime && ['早退', '缺勤', '未签到'].includes(status);
};

// 修改 onSubmit 函数中的验证逻辑
const onSubmit = () => {
    // 检查是否选择了补签日期
    if (!formData.value.retroactiveDate) {
        ElMessage({
            message: '请选择补签日期',
            type: 'warning'
        });
        return;
    }

    // 检查是否有可补签的时间段（根据新规则）
    const hasMorningOption = canSignMorning(attendanceRecord.value.morningStatus);
    const hasAfternoonOption = canSignAfternoon(attendanceRecord.value.afternoonStatus);

    if (!hasMorningOption && !hasAfternoonOption) {
        if (formData.value.retroactiveDate === getCurrentDateStr()) {
            ElMessage({
                message: '当天当前时间不符合补签条件',
                type: 'warning'
            });
        } else {
            ElMessage({
                message: '当前日期无需补签',
                type: 'warning'
            });
        }
        return;
    }

    // 检查是否选择了补签时间段
    if (!formData.value.timeBucket) {
        ElMessage({
            message: '请选择补签时间段',
            type: 'warning'
        });
        return;
    }

    // 检查补签事由
    if (!formData.value.reason) {
        ElMessage({
            message: '请填写补签事由说明',
            type: 'warning'
        });
        return;
    }

    request({
        url: "/cardReplacementApplication/insert",
        method: "post",
        data: {
            ...formData.value
        }
    }).then(resp => {
        ElMessage.primary(resp.msg);
        emits('ref-table');
    })
}

// 修改 watch 中的逻辑
watch(
    () => formData.value.retroactiveDate,
    (newDate, oldDate) => {
        console.log('补签日期发生变化:', newDate);

        if (newDate) {
            // 判断选择的日期是否大于当前日期
            const selectedDate = new Date(newDate);
            const currentDate = new Date();

            // 将时间部分设置为0，只比较日期部分
            selectedDate.setHours(0, 0, 0, 0);
            currentDate.setHours(0, 0, 0, 0);

            if (selectedDate > currentDate) {
                ElMessage({
                    message: '还未到达选择的日期，请选择今天或之前的日期',
                    type: 'warning'
                });
                // 清空选择的日期
                formData.value.retroactiveDate = '';
                return;
            }

            request({
                url: '/attendanceRecord/findByRecordDate',
                method: 'get',
                params: {
                    userId: user.employeeId,
                    recordDate: formData.value.retroactiveDate
                }
            }).then(res => {
                console.log("查询结果", res.data);
                attendanceRecord.value = res.data;
                formData.value.attendanceCycle = res.data.attendanceCycle;
                formData.value.startTime = res.data.recordDate + ' ' + attendanceRule.value.workStart;
                formData.value.endTime = res.data.recordDate + ' ' + attendanceRule.value.workEnd;
            })

            // 获取选择日期对应的星期
            const days = ['日', '一', '二', '三', '四', '五', '六'];
            const dayOfWeek = selectedDate.getDay();
            console.log('星期:', days[dayOfWeek]);

            formData.value.week = '星期' + days[dayOfWeek];
        }
    }
)

const isVisible = ref(false)
// 复制添加
const add = () => {
    isVisible.value = true
    router.push('./insert.vue')
}
//修改显示
const EditDisplay = ref(false)
//编辑
const Editor = () => {
    EditDisplay.value = true
}

//删除操作
const open = () => {
    ElMessageBox.confirm(
        '你确定要删除吗?',
        '通知',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功',

            })
            emit("ref-table")
        })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '取消操作',
            })
        })
}

// 设置当前日期时间
const setCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    formData.value.applicationDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 组件挂载时设置当前日期时间
onMounted(() => {
    setCurrentDateTime();
    loadAttendanceRules();
})

</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
    height: 6px;
    background-color: #ccebf7;
    border-radius: 3px;
    display: flex;
    width: 100%;
    /* 确保进度条容器宽度占满父容器 */
    overflow: hidden;
    /* 防止子元素溢出 */
}

.progress {
    width: 8%;
    height: 10;
    background-color: #61c3ea;
    border-radius: 3px 0 0 3px;
    transition: width 0.3s ease;
    /* 添加宽度变化的过渡效果 */
}

.bottom-submit-bar {
    /* position: fixed; */
    /* 固定定位 */
    bottom: 0;
    /* 靠底部 */
    left: 0;
    width: 100%;
    background-color: #fff;
    /* 背景色，可根据需求调整 */
    border-top: 1px solid #eaeaea;
    /* 顶部边框，与页面区分 */
    padding: 12px 24px;
    /* 内边距，适配截图里的间距风格 */
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /* 按钮靠左，可根据实际需求调整 */
    z-index: 10;
    /* 提高层级，避免被其他内容覆盖 */
}
</style>
